package com.tarena.lbs.test.threadlocal;

import com.tarena.lbs.common.passport.principle.UserPrinciple;

/**
 * 封装 ThreadLocal实现对象
 * 对外提供 读写的方法
 */
public class MyThreadLocalUtils {
    private static ThreadLocal<UserPrinciple> threadLocal = new ThreadLocal<>();

    //定义一个存数据的方法 set
    public static void set(UserPrinciple userPrinciple){
        Thread thread = Thread.currentThread();
        System.out.println("当前set存储数据的线程:"+thread.getId());
        threadLocal.set(userPrinciple);
    }
    //定义一个取数据的方法 get
    public static UserPrinciple get(){
        Thread thread = Thread.currentThread();
        System.out.println("当前get存储数据的线程:"+thread.getId());
        return threadLocal.get();
    }
    //为了防止线程复用产生 数据错乱,我们需要在准备一个清空方法
    public static void clear(){
        Thread thread = Thread.currentThread();
        System.out.println("当前set存储数据的线程:"+thread.getId());
        threadLocal.remove();
    }

}
